from rest_framework import serializers
from ..utils.literUtils import emptyValue
from ..models.Publications import *

class JournalListQuerySerializer(serializers.Serializer):
    name = serializers.CharField(required=False,allow_blank=True)
    zh_name = serializers.CharField(required=False,allow_blank=True)
    abbreviation = serializers.CharField(required=False,allow_blank=True)
    website = serializers.CharField(required=False,allow_blank=True)
    description = serializers.CharField(required=False,allow_blank=True)
    subjects = serializers.CharField(required=False,allow_blank=True)
    institutions = serializers.CharField(required=False,allow_blank=True)
    departments = serializers.CharField(required=False,allow_blank=True)
    
    issn = serializers.CharField(required=False,allow_blank=True)
    cas = serializers.CharField(required=False,allow_blank=True)
    impact_factor = serializers.CharField(required=False,allow_blank=True)
    founding_datej = serializers.CharField(required=False,allow_blank=True)
    contact_emailj = serializers.CharField(required=False,allow_blank=True)
    publication_cycle = serializers.ListField(required=False)
    
    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False,allow_blank=True)
    sort_order = serializers.CharField(required=False,allow_blank=True)
    
    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "name" in attrs:
            attrs["name"] = attrs["name"].strip()
            if attrs["name"] == "":
                attrs.pop("name")
        if "zh_name" in attrs:
            attrs["zh_name"] = attrs["zh_name"].strip()
            if attrs["zh_name"] == "":
                attrs.pop("zh_name")
        if "abbreviation" in attrs:
            attrs["abbreviation"] = attrs["abbreviation"].strip()
            if attrs["abbreviation"] == "":
                attrs.pop("abbreviation")
        if "website" in attrs:
            attrs["website"] = attrs["website"].strip()
            if attrs["website"] == "":
                attrs.pop("website")
        if "description" in attrs:
            attrs["description"] = attrs["description"].strip()
            if attrs["description"] == "":
                attrs.pop("description")
        if "subjects" in attrs:
            attrs["subjects"] = attrs["subjects"].strip()
            if attrs["subjects"] == "":
                attrs.pop("subjects")
        if "institutions" in attrs:
            attrs["institutions"] = attrs["institutions"].strip()
            if attrs["institutions"] == "":
                attrs.pop("institutions")
        if "departments" in attrs:
            attrs["departments"] = attrs["departments"].strip()
            if attrs["departments"] == "":
                attrs.pop("departments")
        if "issn" in attrs:
            attrs["issn"] = attrs["issn"].strip()
            if attrs["issn"] == "":
                attrs.pop("issn")
        if "cas" in attrs:
            attrs["cas"] = attrs["cas"].strip()
            if attrs["cas"] == "":
                attrs.pop("cas") 
        if "impact_factor" in attrs:
            attrs["impact_factor"] = attrs["impact_factor"].strip()
            if attrs["impact_factor"] == "":
                attrs.pop("impact_factor")
        if "founding_datej" in attrs:
            attrs["founding_datej"] = attrs["founding_datej"].strip()
            if attrs["founding_datej"] == "":
                attrs.pop("founding_datej")
        if "contact_emailj" in attrs:
            attrs["contact_emailj"] = attrs["contact_emailj"].strip()
            if attrs["contact_emailj"] == "":
                attrs.pop("contact_emailj")
        if "publication_cycle" in attrs:
            if len(attrs["publication_cycle"]) == 0: attrs.pop("publication_cycle")
        if ("name" not in attrs or attrs["name"] == "") and ("zh_name" not in attrs or attrs["zh_name"] == "") and\
            ("abbreviation" not in attrs or attrs["abbreviation"] == "") and ("website" not in attrs or attrs["website"] == "") and\
            ("description" not in attrs or attrs["description"] == "") and ("subjects" not in attrs or attrs["subjects"] == "") and\
            ("institutions" not in attrs or attrs["institutions"] == "") and ("departments" not in attrs or attrs["departments"] == "") and\
            ("issn" not in attrs or attrs["issn"] == "") and ("cas" not in attrs or attrs["cas"] == "") and\
            ("impact_factor" not in attrs or attrs["impact_factor"] == "") and ("founding_datej" not in attrs or attrs["founding_datej"] == "") and\
            ("contact_emailj" not in attrs or attrs["contact_emailj"] == "") and ("publication_cycle" not in attrs or len(attrs["publication_cycle"]) == 0):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title": "名称：","dataIndex": "name","type": "CharField"},
                {"title": "中文名：","dataIndex": "zh_name","type": "CharField"},
                {"title": "简称缩写：", "dataIndex": "abbreviation", "type": "CharField"},
                {"title": "官方网站：", "dataIndex": "website", "type": "CharField"},
                {"title": "简介：", "dataIndex": "description", "type": "CharField"},
                {"title": "研究领域主题：", "dataIndex": "subjects", "type": "ManyToManyField"},
                {"title": "所属机构：", "dataIndex": "institutions", "type": "ManyToManyField"},
                {"title": "所属部门：", "dataIndex": "departments", "type": "ManyToManyField"},
                {"title": "国际标准出版物号：", "dataIndex": "issn", "type": "CharField"},
                {"title": "cas源代码：", "dataIndex": "cas", "type": "CharField"},
                {"title": "影响因子：", "dataIndex": "impact_factor", "type": "CharField"},
                {"title": "创刊日期：", "dataIndex": "founding_datej", "type": "CharField"},
                {"title": "联系邮箱：", "dataIndex": "contact_emailj", "type": "CharField"},
                {"title": "出版周期：", "dataIndex": "publication_cycle", "type": "ForeignKey"},]
        
        
class ConferenceListQuerySerializer(serializers.Serializer):
    name = serializers.CharField(required=False,allow_blank=True)
    zh_name = serializers.CharField(required=False,allow_blank=True)
    abbreviation = serializers.CharField(required=False,allow_blank=True)
    website = serializers.CharField(required=False,allow_blank=True)
    description = serializers.CharField(required=False,allow_blank=True)
    subjects = serializers.CharField(required=False,allow_blank=True)
    institutions = serializers.CharField(required=False,allow_blank=True)
    departments = serializers.CharField(required=False,allow_blank=True)
    
    founding_datec = serializers.CharField(required=False,allow_blank=True)
    contact_emailc = serializers.CharField(required=False,allow_blank=True)
    meeting_cycle = serializers.ListField(required=False)
    
    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False,allow_blank=True)
    sort_order = serializers.CharField(required=False,allow_blank=True)
    
    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "name" in attrs:
            attrs["name"] = attrs["name"].strip()
            if attrs["name"] == "":
                attrs.pop("name")
        if "zh_name" in attrs:
            attrs["zh_name"] = attrs["zh_name"].strip()
            if attrs["zh_name"] == "":
                attrs.pop("zh_name")
        if "abbreviation" in attrs:
            attrs["abbreviation"] = attrs["abbreviation"].strip()
            if attrs["abbreviation"] == "":
                attrs.pop("abbreviation")
        if "website" in attrs:
            attrs["website"] = attrs["website"].strip()
            if attrs["website"] == "":
                attrs.pop("website")
        if "description" in attrs:
            attrs["description"] = attrs["description"].strip()
            if attrs["description"] == "":
                attrs.pop("description")
        if "subjects" in attrs:
            attrs["subjects"] = attrs["subjects"].strip()
            if attrs["subjects"] == "":
                attrs.pop("subjects")
        if "institutions" in attrs:
            attrs["institutions"] = attrs["institutions"].strip()
            if attrs["institutions"] == "":
                attrs.pop("institutions")
        if "departments" in attrs:
            attrs["departments"] = attrs["departments"].strip()
            if attrs["departments"] == "":
                attrs.pop("departments")
        if "founding_datec" in attrs:
            attrs["founding_datec"] = attrs["founding_datec"].strip()
            if attrs["founding_datec"] == "":
                attrs.pop("founding_datec")
        if "contact_emailc" in attrs:
            attrs["contact_emailc"] = attrs["contact_emailc"].strip()
            if attrs["contact_emailc"] == "":
                attrs.pop("contact_emailc")
        if "meeting_cycle" in attrs:
            if len(attrs["meeting_cycle"]) == 0: attrs.pop("meeting_cycle")
        if ("name" not in attrs or attrs["name"] == "") and ("zh_name" not in attrs or attrs["zh_name"] == "") and\
            ("abbreviation" not in attrs or attrs["abbreviation"] == "") and ("website" not in attrs or attrs["website"] == "") and\
            ("description" not in attrs or attrs["description"] == "") and ("subjects" not in attrs or attrs["subjects"] == "") and\
            ("institutions" not in attrs or attrs["institutions"] == "") and ("departments" not in attrs or attrs["departments"] == "") and\
            ("founding_datec" not in attrs or attrs["founding_datec"] == "") and ("contact_emailc" not in attrs or attrs["contact_emailc"] == "") and\
            ("meeting_cycle" not in attrs or len(attrs["meeting_cycle"]) == 0):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title": "名称：","dataIndex": "name","type": "CharField"},
                {"title": "中文名：","dataIndex": "zh_name","type": "CharField"},
                {"title": "简称缩写：", "dataIndex": "abbreviation", "type": "CharField"},
                {"title": "官方网站：", "dataIndex": "website", "type": "CharField"},
                {"title": "简介：", "dataIndex": "description", "type": "CharField"},
                {"title": "研究领域主题：", "dataIndex": "subjects", "type": "ManyToManyField"},
                {"title": "所属机构：", "dataIndex": "institutions", "type": "ManyToManyField"},
                {"title": "所属部门：", "dataIndex": "departments", "type": "ManyToManyField"},
                {"title": "创始日期：", "dataIndex": "founding_datec", "type": "CharField"},
                {"title": "联系邮箱：", "dataIndex": "contact_emailc", "type": "CharField"},
                {"title": "开会周期：", "dataIndex": "meeting_cycle", "type": "ForeignKey"},]
        
        
class BookListQuerySerializer(serializers.Serializer):
    name = serializers.CharField(required=False,allow_blank=True)
    zh_name = serializers.CharField(required=False,allow_blank=True)
    abbreviation = serializers.CharField(required=False,allow_blank=True)
    website = serializers.CharField(required=False,allow_blank=True)
    description = serializers.CharField(required=False,allow_blank=True)
    subjects = serializers.CharField(required=False,allow_blank=True)
    institutions = serializers.CharField(required=False,allow_blank=True)
    departments = serializers.CharField(required=False,allow_blank=True)
 
    publish_date = serializers.CharField(required=False,allow_blank=True)
    isbn = serializers.CharField(required=False,allow_blank=True)
    page_number = serializers.CharField(required=False,allow_blank=True)
    language = serializers.ListField(required=False)
    authors = serializers.CharField(required=False,allow_blank=True)
    
    
    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False,allow_blank=True)
    sort_order = serializers.CharField(required=False,allow_blank=True)
    
    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "name" in attrs:
            attrs["name"] = attrs["name"].strip()
            if attrs["name"] == "":
                attrs.pop("name")
        if "zh_name" in attrs:
            attrs["zh_name"] = attrs["zh_name"].strip()
            if attrs["zh_name"] == "":
                attrs.pop("zh_name")
        if "abbreviation" in attrs:
            attrs["abbreviation"] = attrs["abbreviation"].strip()
            if attrs["abbreviation"] == "":
                attrs.pop("abbreviation")
        if "website" in attrs:
            attrs["website"] = attrs["website"].strip()
            if attrs["website"] == "":
                attrs.pop("website")
        if "description" in attrs:
            attrs["description"] = attrs["description"].strip()
            if attrs["description"] == "":
                attrs.pop("description")
        if "subjects" in attrs:
            attrs["subjects"] = attrs["subjects"].strip()
            if attrs["subjects"] == "":
                attrs.pop("subjects")
        if "institutions" in attrs:
            attrs["institutions"] = attrs["institutions"].strip()
            if attrs["institutions"] == "":
                attrs.pop("institutions")
        if "departments" in attrs:
            attrs["departments"] = attrs["departments"].strip()
            if attrs["departments"] == "":
                attrs.pop("departments")
        if "publish_date" in attrs:
            attrs["publish_date"] = attrs["publish_date"].strip()
            if attrs["publish_date"] == "":
                attrs.pop("publish_date")
        if "isbn" in attrs:
            attrs["isbn"] = attrs["isbn"].strip()
            if attrs["isbn"] == "":
                attrs.pop("isbn") 
        if "page_number" in attrs:
            attrs["page_number"] = attrs["page_number"].strip()
            if attrs["page_number"] == "":
                attrs.pop("page_number")
        if "authors" in attrs:
            attrs["authors"] = attrs["authors"].strip()
            if attrs["authors"] == "":
                attrs.pop("authors")
        if "language" in attrs:
            if len(attrs["language"]) == 0: attrs.pop("language")
        if ("name" not in attrs or attrs["name"] == "") and ("zh_name" not in attrs or attrs["zh_name"] == "") and\
            ("abbreviation" not in attrs or attrs["abbreviation"] == "") and ("website" not in attrs or attrs["website"] == "") and\
            ("description" not in attrs or attrs["description"] == "") and ("subjects" not in attrs or attrs["subjects"] == "") and\
            ("institutions" not in attrs or attrs["institutions"] == "") and ("departments" not in attrs or attrs["departments"] == "") and\
            ("isbn" not in attrs or attrs["isbn"] == "") and ("page_number" not in attrs or attrs["page_number"] == "") and\
            ("authors" not in attrs or attrs["authors"] == "") and ("publish_date" not in attrs or attrs["publish_date"] == "") and\
            ("language" not in attrs or len(attrs["language"]) == 0):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title": "名称：","dataIndex": "name","type": "CharField"},
                {"title": "中文名：","dataIndex": "zh_name","type": "CharField"},
                {"title": "简称缩写：", "dataIndex": "abbreviation", "type": "CharField"},
                {"title": "官方网站：", "dataIndex": "website", "type": "CharField"},
                {"title": "简介：", "dataIndex": "description", "type": "CharField"},
                {"title": "研究领域主题：", "dataIndex": "subjects", "type": "ManyToManyField"},
                {"title": "所属机构：", "dataIndex": "institutions", "type": "ManyToManyField"},
                {"title": "所属部门：", "dataIndex": "departments", "type": "ManyToManyField"},
                {"title": "出版日期：", "dataIndex": "publish_date", "type": "CharField"},
                {"title": "国际标准书号：", "dataIndex": "isbn", "type": "CharField"},
                {"title": "总页码：", "dataIndex": "page_number", "type": "CharField"},
                {"title": "作者列表：", "dataIndex": "authors", "type": "ManyToManyField"},
                {"title": "语言：", "dataIndex": "language", "type": "ForeignKey"},]
        
        
class JournalListSerializer(serializers.ModelSerializer):
    publication_cycle = serializers.SerializerMethodField()
    subjects = serializers.SerializerMethodField()
    institutions = serializers.SerializerMethodField()
    departments = serializers.SerializerMethodField()

    class Meta:
        model = Journal
        fields = ['uuid', 'name', 'zh_name', 'abbreviation', 'website', 'description', 'subjects', 'institutions', 'departments',\
                  'issn', 'cas', 'impact_factor', 'founding_datej', 'contact_emailj', 'publication_cycle']

    def get_publication_cycle(self, obj):
        return "{}({})".format(obj.publication_cycle.zh_name, obj.publication_cycle.name) + "\n"
    
    def get_subjects(self, obj):
        subjects_content = ""
        for subject in obj.subjects.all():
            if emptyValue(subject.v):
                subjects_content += subject.k + "; "
            else:
                subjects_content += subject.k + ' (' + subject.v + '); '
        return subjects_content[:-2]
    
    def get_institutions(self, obj):
        institutions_content = ""
        for institution in obj.institutions.all():
            if emptyValue(institution.zh_name):
                institutions_content += institution.name + '; '
            else:
                institutions_content += institution.name + ' (' + institution.zh_name + '); '
        return institutions_content[:-2]
    
    def get_departments(self, obj):
        departments_content = ""
        for department in obj.departments.all():
            if emptyValue(department.zh_name):
                departments_content += department.name + '; '
            else:
                departments_content += department.name + ' (' + department.zh_name + '); '
        return departments_content[:-2]
        
    @classmethod
    def get_extra_fields_info(self):
        return [{"title":"出版周期", "dataIndex":"publication_cycle", "type":"CharField"},
                {"title":"研究领域主题", "dataIndex":"subjects", "type":"CharField"},
                {"title":"所属机构", "dataIndex":"institutions", "type":"CharField"},
                {"title":"所属部门", "dataIndex":"departments", "type":"CharField"},]
        
        
class ConferenceListSerializer(serializers.ModelSerializer):
    meeting_cycle = serializers.SerializerMethodField()
    subjects = serializers.SerializerMethodField()
    institutions = serializers.SerializerMethodField()
    departments = serializers.SerializerMethodField()

    class Meta:
        model = Conference
        fields = ['uuid', 'name', 'zh_name', 'abbreviation', 'website', 'description', 'subjects', 'institutions', 'departments',\
                  'founding_datec', 'contact_emailc', 'meeting_cycle']

    def get_meeting_cycle(self, obj):
        return "{}({})".format(obj.meeting_cycle.zh_name, obj.meeting_cycle.name) + "\n"
    
    def get_subjects(self, obj):
        subjects_content = ""
        for subject in obj.subjects.all():
            if emptyValue(subject.v):
                subjects_content += subject.k + "; "
            else:
                subjects_content += subject.k + ' (' + subject.v + '); '
        return subjects_content[:-2]
    
    def get_institutions(self, obj):
        institutions_content = ""
        for institution in obj.institutions.all():
            if emptyValue(institution.zh_name):
                institutions_content += institution.name + '; '
            else:
                institutions_content += institution.name + ' (' + institution.zh_name + '); '
        return institutions_content[:-2]
    
    def get_departments(self, obj):
        departments_content = ""
        for department in obj.departments.all():
            if emptyValue(department.zh_name):
                departments_content += department.name + '; '
            else:
                departments_content += department.name + ' (' + department.zh_name + '); '
        return departments_content[:-2]
        
    @classmethod
    def get_extra_fields_info(self):
        return [{"title":"开会周期", "dataIndex":"meeting_cycle", "type":"CharField"},
                {"title":"研究领域主题", "dataIndex":"subjects", "type":"CharField"},
                {"title":"所属机构", "dataIndex":"institutions", "type":"CharField"},
                {"title":"所属部门", "dataIndex":"departments", "type":"CharField"},]
        
        
class BookListSerializer(serializers.ModelSerializer):
    language = serializers.SerializerMethodField()
    subjects = serializers.SerializerMethodField()
    institutions = serializers.SerializerMethodField()
    departments = serializers.SerializerMethodField()
    authors = serializers.SerializerMethodField()

    class Meta:
        model = Book
        fields = ['uuid', 'name', 'zh_name', 'abbreviation', 'website', 'description', 'subjects', 'institutions', 'departments',\
                  'publish_date', 'isbn', 'page_number', 'language', 'authors']

    def get_language(self, obj):
        return "{}({})".format(obj.language.zh_name, obj.language.name) + "\n"
    
    def get_authors(self, obj):
        authors_content = ""
        for author in obj.authors.all():
            if emptyValue(author.zh_name):
                authors_content += author.name + "; "
            else:
                authors_content += author.name + ' (' + author.zh_name + '); '
        return authors_content[:-2]
    
    def get_subjects(self, obj):
        subjects_content = ""
        for subject in obj.subjects.all():
            if emptyValue(subject.v):
                subjects_content += subject.k + "; "
            else:
                subjects_content += subject.k + ' (' + subject.v + '); '
        return subjects_content[:-2]
    
    def get_institutions(self, obj):
        institutions_content = ""
        for institution in obj.institutions.all():
            if emptyValue(institution.zh_name):
                institutions_content += institution.name + '; '
            else:
                institutions_content += institution.name + ' (' + institution.zh_name + '); '
        return institutions_content[:-2]
    
    def get_departments(self, obj):
        departments_content = ""
        for department in obj.departments.all():
            if emptyValue(department.zh_name):
                departments_content += department.name + '; '
            else:
                departments_content += department.name + ' (' + department.zh_name + '); '
        return departments_content[:-2]
        
    @classmethod
    def get_extra_fields_info(self):
        return [{"title":"语言", "dataIndex":"language", "type":"CharField"},
                {"title":"研究领域主题", "dataIndex":"subjects", "type":"CharField"},
                {"title":"所属机构", "dataIndex":"institutions", "type":"CharField"},
                {"title":"所属部门", "dataIndex":"departments", "type":"CharField"},
                {"title":"作者列表", "dataIndex":"authors", "type":"CharField"},]